//练习：在用户路由器user.js下，创建路由器对象，添加用户注册的路由(post /reg)，导出路由器对象；在服务器app.js下引入（./router/user.js），并添加前缀/user
//引入express模块
const express=require('express');
//引入连接池
const pool=require('../pool.js');
//创建路由器对象
const r=express.Router();

//添加路由
//1.用户注册
//post   /reg
r.post('/reg',(req,res)=>{
	//1.1获取post传递的数据
	let obj=req.body;
	console.log(obj);
	//1.2验证数据是否为空
	if(!obj.uname){
		res.send({code:401,msg:'uname required'});
		return;
	}
	if(!obj.upwd){
		res.send({code:402,msg:'upwd required'});
		return;
	}
	if(!obj.email){
		res.send({code:403,msg:'email required'});
		return;
	}
	if(!obj.phone){
		res.send({code:404,msg:'phone required'});
		return;
	}
	//1.3执行SQL语句,插入到用户表中
	pool.query('INSERT INTO xz_user SET ?',[obj],(err,result)=>{
		if(err) throw err;
		console.log(result);
	});
	res.send({code:200,msg:'reg success'});
});
//2.用户登录
r.post('/login',(req,res)=>{
	let obj1=req.body;
	console.log(obj1);
	if(!obj1.uname){
		res.send({code:401,msg:'uname required'});
		return;
	}
	if(!obj1.upwd){
		res.send({code:402,msg:'upwd required'});
		return;
	};
	pool.query('SELECT * FROM xz_user WHERE uname=? AND upwd=?',[obj1.uname,obj1.upwd],(err,result)=>{
		if(err) throw err;
		//结果是数组
		console.log(result);
		//如果数组长度为0,说明登陆失败;否则登陆成功
		if(result.length===0){
			res.send({code:301,msg:'login err'})
		}else{
			res.send({code:200,msg:'login suc'})
		}
	});
	//res.send('登陆成功');
});
//3.修改用户资料
r.get('/update',(req,res)=>{
	//3.1获取查询字符串传递的数据
	let obj2=req.query;
	console.log(obj2);
	//3.2使用for-in循环遍历对象属性,如果哪一项的值为空,响应哪一项是必须的
	//访问每一个属性
	let i=400;
	for(let key in obj2){
		i++;
		//key   属性名   obj[key] 对应的属性值
		//console.log(key,obj2[key]);
		//判断属性值是否为空
		if(!obj2[key]){
			res.send({code:i,msg:key+'required'});
			return;
		};
	};
	pool.query('UPDATE xz_user SET ? WHERE uid=?',[obj2,obj2.uid],(err,result)=>{
		if(err) throw err;
		console.log(result);
		if (result.affectedRows===0){
			res.send({code:301,msg:'update err'});
		}else{
			res.send({code:200,msg:'update success'})
		}
	});
});
//4.查询数据
r.get('/list',(req,res)=>{
	let obj3=req.query;
	console.log(obj3);
	if(!obj3.page){
		obj3.page=1;
	};
	if(!obj3.data){
		obj3.data=3;
	};
	let a=parseInt(obj3.page);
	let b=parseInt(obj3.data);
	let c=(a-1)*b
	pool.query('SELECT * FROM xz_user LIMIT ?, ?',[c,b],(err,result)=>{
		if(err) throw err;
		res.send(result);
	});
});

//导出路由器对象
module.exports=r;